<template>
  <px-dialog v-model="visible" :title="type != 'preview' ? '导入校验报表' : '校验报表详情'" @close="cancel">
    <div>
      <px-form ref="formRef" :model="queryParams" label-width="80px">
        <px-form-item label="PO号" required>
          <px-input v-model="queryParams.po" placeholder="请选输入PO号" :disabled="type != 'add'" />
        </px-form-item>
        <px-form-item label="PO类型" required>
          <px-select v-model="queryParams.type" placeholder="请选择PO类型" style="width: 100%" :disabled="type != 'add'">
            <px-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="文件" required v-if="type != 'preview'">
          <px-upload
            v-model:file-list="fileList"
            class="upload-demo"
            :limit="limit"
            drag
            action="#"
            :auto-upload="false"
            :on-change="onChange"
            accept="xls,xlsx"
            :disabled="type == 'preview'"
          >
            <px-icon class="px-icon--upload"><upload-filled /></px-icon>
            <div class="el-upload__text">拖拽到这里或<em>点击上传</em></div>
            <template #tip>
              <div class="px-upload__tip">文件需小于1G</div>
            </template>
          </px-upload>
        </px-form-item>
        <div v-if="sheetList && sheetList.length && type != 'preview'" class="preview-container">
          <px-scrollbar class="preview-table-scroll">
            <div v-for="(item, index) in sheetList" v-show="item.isSelected" :key="index" class="excelTable" v-html="item.content" />
          </px-scrollbar>
        </div>
        <div v-if="poDetailList && poDetailList.length && (!sheetList || !sheetList.length)">
          <div class="excel-title" v-for="(item,index) in poRecordInfo.project.split('_')" :key="index">{{ item}}</div>
          <px-scrollbar class="preview-table-scroll">
            <px-table :data="poDetailList" class="equip-table" height="500" border>
              <template #empty>
                <px-empty />
              </template>
              <px-table-column prop="item" label="项次" min-width="80" />
              <px-table-column prop="particulars" label="内容" min-width="100" />
              <px-table-column prop="unit" label="单位" min-width="100" />
              <px-table-column prop="quantity" label="数量" min-width="100" />
              <px-table-column prop="eqpUnitPrice" label="设备单价" min-width="100" />
              <px-table-column prop="eqpTotalPrice" label="设备总价" min-width="100" />
              <px-table-column prop="unitPrice" label="安装单价" min-width="100" />
              <px-table-column prop="totalPrice" label="安装总价" min-width="100" />
              <px-table-column prop="specification" label="规格" min-width="100" />
              <px-table-column prop="remark" label="备注" min-width="100" />
            </px-table>
          </px-scrollbar>
        </div>
      </px-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancel">取消</px-button>
        <px-button type="primary" @click="confirmUpload">确定</px-button>
      </span>
    </template>
  </px-dialog>
</template>

<script setup>
import { computed, ref, reactive, watchEffect } from "vue";
import { UploadFilled } from "@px-ui/icons-vue";
import { PxMessage } from "px-ui";
import * as XLSX from "xlsx/xlsx.mjs";
import { queryPoDetail } from "@/api/machineReport";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 1
  },
  folderData: {
    type: Object,
    default: () => {}
  },
  actionUrl: {
    type: String,
    default: ""
  },
  type: {
    type: String,
    default: ""
  },
  poRecordId: {
    type: String,
    default: ""
  }
});
const emits = defineEmits(["update:visible", "uploadAction"]);

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});
const queryParams = reactive({
  po: "",
  type: ""
});
const formRef = ref();

const fileList = ref([]);

const sheetList = ref([]);

const ACCEPTED_EXTENSIONS = ["xls", "xlsx"];

const typeList = ref([
  {
    label: "计划PO",
    value: "计划PO"
  },
  {
    label: "OPEN PARTS",
    value: "OPENPARTS"
  }
]);
const poDetailList = ref([]);
const poRecordInfo = ref({});

/**
 * 文件选择改变时触发
 */
function onChange(file, fileListVal) {
  // const extension = file.name.split(".").pop().toLowerCase();
  // if (!ACCEPTED_EXTENSIONS.includes(extension)) {
  //   PxMessage.error("仅支持 doc, docx, xls, xlsx, ppt, pptx, txt, pdf格式的文件");
  //   fileList.value.pop();
  //   return;
  // }
  const fileSizeLimit = file.size / 1024 / 1024 / 1024 < 1;
  if (!fileSizeLimit) {
    PxMessage.error("文件大小需小于1G");
    fileList.value.pop();
    return;
  }
  fileList.value = fileListVal;
  const fileReader = new FileReader();
  fileReader.onload = ev => {
    try {
      sheetList.value = [];
      const data = ev.target.result;
      previewExcel(data);
    } catch (e) {
      this.$message.warning("文件类型不正确！");
    }
  };
  fileReader.readAsBinaryString(fileListVal[0].raw);
}

/**
 * 提交请求
 * 处理上传逻辑
 */
const confirmUpload = async () => {
  if(props.type == 'preview'){
    cancel();
  }else{
    formRef.value?.validate(async (valid, fields) => {
        if (valid) {
          if (!queryParams.po) {
            return PxMessage.error("请填写PO号");
          }
          if (!queryParams.type) {
            return PxMessage.error("请选择PO类型");
          }
          if (fileList.value.length === 0) {
            return PxMessage.error("请选择要上传的文件");
          }
          let obj = {
            poType: queryParams.type,
            poNo: queryParams.po,
            fileList: fileList.value
          };
          emits("uploadAction", obj);
        } else {
          console.log("error submit!", fields);
        }
      });
  }
  
};

const previewExcel = data => {
  let workbook = XLSX.read(data, { type: "binary" });
  let sheetFileList = workbook.SheetNames;
  sheetFileList.forEach((item, index) => {
    let ws = workbook.Sheets[item];
    let fileContent = "";
    try {
      // 把excel文件流转化为html字符串，以便于v-html使用
      fileContent = XLSX.utils.sheet_to_html(ws);
      sheetList.value.push({
        name: item,
        isSelected: index == 0,
        content: fileContent
      });
    } catch (err) {
      console.error(err);
    }
  });
};

const cancel = () => {
  fileList.value = [];
  emits("update:visible", false);
};
const getDetailTable = async () => {
  let res = await queryPoDetail({ poRecordId: props.poRecordId });
  poRecordInfo.value = res?.machinePORecord;
  queryParams.po = res?.machinePORecord?.poNumber;
  queryParams.type = res?.machinePORecord?.poType;
  poDetailList.value = res?.machinePODetailList || [];
};
watchEffect(() => {
  if (props.poRecordId) {
    getDetailTable();
  } else {
    poDetailList.value = [];
  }
});
defineExpose({
  cancel
});
</script>

<style lang="scss" scoped>
.upload-demo {
  width: 100%;
}

p {
  line-height: 36px;

  .label {
    display: inline-block;
    width: 80px;
    color: #000;
    text-align: right;
  }
}

.preview-container {
  box-sizing: border-box;
  width: 100%;
  max-height: 500px;
  padding: 0 16px;
  overflow: hidden;
}

:deep(.px-scrollbar) {
  &.preview-table-scroll {
    position: relative;
    width: 101%;
    height: 500px;
  }
}

:deep(.excelTable) {
  box-sizing: border-box;
  padding: 0 10px;

  table {
    min-width: 100%;
    border-collapse: collapse;
    th {
      font-weight: bold;
      background-color: #f5f5f5;
    }

    th,
    td {
      padding: 8px;
      color: rgb(0, 0, 0, 0.8);
      text-align: left;
      border: 1px solid #ddd;
    }

    .header {
      color: white;
      background-color: #4caf50;
    }
  }
}
.excel-title{
  color: #000000;
  font-size: 14px;
  font-weight:bold;
  text-align: center;
  margin-bottom: 8px;
}
</style>
